package com.cqjtu.tto.controller;

import com.cqjtu.tto.dao.pojo.Project;
import com.cqjtu.tto.service.FolderService;
import com.cqjtu.tto.service.impl.FolderServiceImpl;
import com.cqjtu.tto.vo.Results;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

@RestController
@Api(tags = "文件夹管理模块")
public class FolderController {
    @Autowired
    FolderService folderService;

    @GetMapping("download")
    @ApiOperation(value = "文件下载")
    public String download(HttpServletResponse httpServletResponse, String pro_name) throws Exception{
        folderService.packge(pro_name);                                            //给项目文件夹打包
        String downurl = "/root/"+pro_name+".zip";
        File file = folderService.downloadFile(downurl);
        String filename  = file.getName();
        if (file.exists()) { //判断文件父目录是否存在
            httpServletResponse.setContentType("application/zip;charset=UTF-8");
            httpServletResponse.setCharacterEncoding("UTF-8");
            // response.setContentType("application/force-download");
            httpServletResponse.setHeader("Content-Disposition", "attachment;fileName=" + java.net.URLEncoder.encode(filename, "UTF-8"));
            byte[] buffer = new byte[1024];
            FileInputStream fis = null; //文件输入流
            BufferedInputStream bis = null;
            OutputStream os = null; //输出流
            try {
                os = httpServletResponse.getOutputStream();
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer);
                    i = bis.read(buffer);
                }

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("----------file download---" + filename);
            try {
                bis.close();
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @PostMapping("FolderAll")
    @ApiOperation(value = "所有文件夹")
    public Results folderAll(Long builder_id){return folderService.selectAll(builder_id);}

}
